package com.atguigu.tingshu.album.service.impl;

import com.atguigu.tingshu.album.config.VodConstantProperties;
import com.atguigu.tingshu.album.service.VodService;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.UploadFileUtil;
import com.atguigu.tingshu.vo.album.TrackMediaInfoVo;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.qcloud.vod.VodUploadClient;
import com.qcloud.vod.model.VodUploadRequest;
import com.qcloud.vod.model.VodUploadResponse;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.vod.v20180717.VodClient;
import com.tencentcloudapi.vod.v20180717.models.*;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Service
@Slf4j
public class VodServiceImpl implements VodService {

    @Autowired
    private VodConstantProperties vodConstantProperties;

    @Autowired
    private VodUploadClient vodUploadClient;

    @Autowired
    private VodClient vodClient;

    @Override
    @SneakyThrows
    public Map<String, Object> uploadTrack(MultipartFile file) {
        // todo: 腾讯云音视频文件上传文档  https://cloud.tencent.com/document/product/266/10276
        // 声音上传临时目录
        String tempPath = UploadFileUtil.uploadTempPath(vodConstantProperties.getTempPath(), file);
        // 构建上传请求对象
        VodUploadRequest request = new VodUploadRequest();
        // 设置视频本地地址
        request.setMediaFilePath(tempPath);
        // 指定任务流
        request.setProcedure(vodConstantProperties.getProcedure());
        // 调用上传方法
        VodUploadResponse response = vodUploadClient.upload(vodConstantProperties.getRegion(), request);
        // 创建map对象
        HashMap<String, Object> map = new HashMap<>();
        map.put("mediaFileId", response.getFileId());
        map.put("mediaUrl", request.getMediaFilePath());
        return map;
    }

    @Override
    public TrackMediaInfoVo getTrackMediaInfo(String mediaFileId) {
        // todo: 腾讯云音视频文件上传文档  https://cloud.tencent.com/document/product/266/31763
        try {
            DescribeMediaInfosRequest request = new DescribeMediaInfosRequest();
            request.setFileIds(new String[]{mediaFileId});
            DescribeMediaInfosResponse response = vodClient.DescribeMediaInfos(request);
            log.info("声音元数据信息：{}", DescribeMediaInfosResponse.toJsonString(response));
            // 获取媒体信息，如果不为空
            MediaInfo[] mediaInfoSet = response.getMediaInfoSet();
            if (mediaInfoSet != null && mediaInfoSet.length > 0) {
                MediaInfo mediaInfo = mediaInfoSet[0];
                TrackMediaInfoVo trackMediaInfoVo = new TrackMediaInfoVo();
                trackMediaInfoVo.setDuration(mediaInfo.getMetaData().getDuration());
                trackMediaInfoVo.setSize(mediaInfo.getMetaData().getSize());
                trackMediaInfoVo.setType(mediaInfo.getBasicInfo().getType());
                trackMediaInfoVo.setMediaUrl(mediaInfo.getBasicInfo().getMediaUrl());
                return trackMediaInfoVo;
            }
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
            throw new GuiguException(ResultCodeEnum.SERVICE_ERROR);
        }
        return null;
    }

    @Override
    public void removeTrackMedia(String mediaFileId) {
        try {
            DeleteMediaRequest request = new DeleteMediaRequest();
            request.setFileId(mediaFileId);
            DeleteMediaResponse response = vodClient.DeleteMedia(request);
            log.info("被删除的声音元数据信息：{}", DescribeMediaInfosResponse.toJsonString(response));
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getPlayToken(String mediaFileId) {
        String AppId = vodConstantProperties.getAppId();
        String FileId = mediaFileId;
        String AudioVideoType = "Original";
        Integer RawAdaptiveDefinition = 10;
        Integer ImageSpriteDefinition = 10;
        Integer CurrentTime = Math.toIntExact(new Date().getTime() / 1000);//播放器签名的派发时间为
        Integer PsignExpire = CurrentTime + 60 * 60 * 2;//播放器签名的过期时间，根据录制最长时间设置，如：两小时
        String UrlTimeExpire = String.valueOf(PsignExpire);//防盗链的过期时间
        String PlayKey = vodConstantProperties.getPlayKey();//播放密钥
        HashMap<String, Object> urlAccessInfo = new HashMap<String, Object>();
        urlAccessInfo.put("t", UrlTimeExpire);
        HashMap<String, Object> contentInfo = new HashMap<String, Object>();
        contentInfo.put("audioVideoType", AudioVideoType);
        contentInfo.put("rawAdaptiveDefinition", RawAdaptiveDefinition);
        contentInfo.put("imageSpriteDefinition", ImageSpriteDefinition);

        Algorithm algorithm = Algorithm.HMAC256(PlayKey);
        String token = JWT.create().withClaim("appId", AppId).withClaim("fileId", FileId)
                .withClaim("contentInfo", contentInfo)
                .withClaim("currentTimeStamp", CurrentTime).withClaim("expireTimeStamp", PsignExpire)
                .withClaim("urlAccessInfo", urlAccessInfo).sign(algorithm);
        log.info("声音播放凭证token:" + token);
        return token;
    }
}
